<template>
  <Dialog
    :title="props.editId ? '修改' : '新增'"
    @handle-confirm="handleConfirm"
    @closed="handleDialogClosed"
    @open="handleDialogOpen"
  >
    <el-form
      ref="formEl"
      :model="roleForm"
      :rules="rules"
      label-width="100px"
      label-position="right"
      v-loading="formLoading"
      v-if="!formLoading"
    >
      <el-form-item label="部门名称：" prop="displayName">
        <el-input v-model="roleForm.displayName" placeholder="请输入部门名称" />
      </el-form-item>
      <el-form-item label="所属部门：" prop="parentId">
        <DepartmentSelect
          :check-child="false"
          :current-id="currentId"
          v-model="roleForm.parentId"
        />
      </el-form-item>
    </el-form>
  </Dialog>
</template>

<script setup lang="ts">
import { ElMessage } from 'element-plus'
import { reactive, ref } from 'vue'

import DepartmentSelect from '@/components/DepartmentSelect/index.vue'
import Dialog from '@/components/Dialog/index.vue'
import {
  addDepartment,
  getDepartment,
  updateDepartment,
} from '@/http/department'
import type { IAddDepartment } from '@/http/types/department'
import { IElForm } from '@/types/element-plus'

const props = defineProps({
  editId: {
    type: String,
    default: '',
  },
})
interface EmitsType {
  (e: 'success'): void
  (e: 'update:editId', value: number | null): void
}
const emit = defineEmits<EmitsType>()

const formEl = ref<IElForm>()

const roleForm = ref<IAddDepartment>({
  displayName: '',
  parentId: '',
})

const formLoading = ref(false)
const rules = reactive({
  displayName: [{ required: true, message: '请输入部门名称', trigger: 'blur' }],
})

const handleConfirm = async () => {
  try {
    await formEl.value?.validate()
    const data = {
      displayName: roleForm.value.displayName,
      parentId: roleForm.value.parentId || undefined,
    }
    if (props.editId) {
      await updateDepartment(props.editId, data)
    } else {
      await addDepartment(data)
    }
    emit('success')
    ElMessage.success('保存成功')
  } catch (err) {
    console.error(err)
  }
}
const handleDialogClosed = () => {
  emit('update:editId', null)
  formEl.value?.resetFields()
  currentId.value = ''
  roleForm.value = {
    displayName: '',
    parentId: '',
  }
}
const handleDialogOpen = async () => {
  formLoading.value = true
  await getDepartmentInfo().finally(() => {
    formLoading.value = false
  })
}
const currentId = ref('')
const getDepartmentInfo = async () => {
  if (!props.editId) return
  const res = await getDepartment(props.editId)
  roleForm.value.displayName = res.displayName
  roleForm.value.parentId = res.parentId
  currentId.value = res.id || ''
}
</script>

<style lang="scss" scoped>
// .departmentForm{}
</style>
